import { useModel } from 'umi';
import { getPermissions } from '@/services/user';

function getItems(arr: API.MenuItem[], id: number | string | undefined): string[] {
  const res = [];
  const target = arr.find((item) => item.id === id);
  if (target) {
    res.unshift(target.name!);
    res.unshift(...getItems(arr, target.pid));
  }
  return res;
}

function getBtns(arr: API.MenuItem[], data: API.MenuItem[]): string[] {
  return arr.map((item: API.MenuItem) => {
    const relativePath = getItems(data, item.id);
    const path = relativePath.reduce((total, curr) => {
      return `${total}.${curr}`;
    }, '');
    return path!.substring(1);
  });
}

export const fetchPermissions = async () => {
  const { data } = await getPermissions();
  return data
    ? {
        menus: data.filter((item) => item.type === 'menu').map((item) => item.name),
        btns: getBtns(
          data.filter((item) => item.type === 'btn'),
          data,
        ),
      }
    : {};
};

export default () => {
  const { setInitialState } = useModel('@@initialState');
  const _fetchPermissions = async () => {
    const permissions = await fetchPermissions();
    await setInitialState((s) => ({
      ...s,
      permissions,
    }));
  };

  return { fetchPermissions: _fetchPermissions };
};
